import { generateGridList } from '../../utils/util'

// pages/main/main.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: getApp().globalData.IMG_URL,
    // 自定义导航栏的高度
    statusBarHeight: getApp().globalData.statusBarHeight,
    navBarHeight: getApp().globalData.navBarHeight,
    winWidth: getApp().globalData.winWidth,
    winHeight: getApp().globalData.winWidth,
    // tab切换 
    currentTab: 0,

    crossAxisCount: 2,
    crossAxisGap: 2,
    mainAxisGap: 2,
    storServiceList: null,
    storeClassifyList: generateGridList(5, 0),

    gridListTop: null,  //generateGridList(10, 5)
    goodsList: null, //generateGridList(20, 2)
    tabViewListAndPageGridList: null,
    searchHots: ["腊猪脚", "大米", "西瓜", "烧烤", "理发", "老凯里苗家酸汤鱼"],
  },

  /**
   * 生命周期函数--监听页面加载  
   */
  onLoad() {
    this.onPullDownRefresh()
    // console.error(JSON.stringify(this.data))
    // console.error("log baseImgUrl = "+JSON.stringify(this.data.baseImgUrl))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    var that = this
    // const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL

    const storeServiceUrl = preUrl + "fc/storeFunc/client/anon/listForEnable"
    wx.request({
      url: storeServiceUrl,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: 5
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        wx.stopPullDownRefresh()
        if (res.data.code == 200 && res.data.result.records.length > 0) {
          that.setData({ storServiceList: res.data.result.records })
          console.error(JSON.stringify(that.data.storServiceList))
        } else {
          console.error(JSON.stringify(res))
        }
      },
    })

    // 推荐商品
    const goodsPageForHomeUrl = preUrl + "fc/goods/client/anon/pageForHomeList"
    wx.request({
      url: goodsPageForHomeUrl,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: 30
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const length = res.data.result.records.length
          for (let index = 0; index < length; index++) {
            const item = res.data.result.records[index]
            if (item != null) {
              const cover = item.goodsCover;
              if (cover.includes(',')) {
                const firstIndex = cover.indexOf(',');
                const coverReal = cover.substring(0, firstIndex);
                item.goodsCover = coverReal
              } else {
                item.goodsCover = cover
              }
            }
          }
          that.setData({ goodsList: res.data.result.records })
          console.info("goodsList = " + JSON.stringify(that.data.goodsList))
        } else {
          console.info(JSON.stringify(res))
        }
      },
    })

    // 分类
    const classifyUrl = preUrl + "fc/client/industry/pageForHomeIndustry"
    wx.request({
      url: classifyUrl,
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: 30
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          that.setData({ gridListTop: res.data.result.records })

          // console.info("处理tab分栏数据 1")
          const tabViewListAndPageGridList = that.createTabViewListAndPageGridList2(that.data.gridListTop)
          // console.info("处理tab分栏数据 2" + JSON.stringify(tabViewListAndPageGridList))
          that.setData({ tabViewListAndPageGridList: tabViewListAndPageGridList })
          // console.error("处理tab分栏数据 3" + JSON.stringify(that.data.tabViewListAndPageGridList))
        } else {
          console.info(JSON.stringify(res))
        }
      },
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  createTabViewListAndPageGridList2(classifyList: Array<any>) {
    const listLength = classifyList.length
    // console.error("classifyList.length：数据大小 " + listLength)
    const hasMore = listLength % 15 != 0;
    // console.error("classifyList.length：是否有多余 " + hasMore)
    const indexFullNum = Math.trunc(listLength / 15);
    // console.error("classifyList.length：满页数 " + indexFullNum)
    const index = hasMore ? indexFullNum + 1 : indexFullNum;
    // console.error("classifyList.length：最终页数 ：" + index)

    let pageSize = 10 // 高度 
    // let pageSize = 15 // 高度 410rpx

    const ans = []
    for (let i = 0; i < index; i++) {
      if (i != index - 1) {
        const start = i * pageSize
        const end = i * pageSize + pageSize;
        // console.error("classifyList.length：sub ：" + start + ", " + end)
        ans.push(classifyList.slice(start, end))
      } else {
        const start = i * pageSize
        // console.error("classifyList.length：sub ：" + start)
        ans.push(classifyList.slice(start))
      }
    }
    // console.error("ans 大小：-----------------------------" + ans.length)
    // console.error(JSON.stringify(ans))
    // console.error("ans 大小：--------------------------------------------------------------")
    return ans
  },
  /** 
   * 滑动切换tab 
   */
  bindChange(e: any) {
    var current = e.detail.current
    // console.error(current);

    var that = this;
    that.setData({ currentTab: current });
    // console.error(JSON.stringify(that.data));

  },
  /**
   * 点击切换tab 
   * @param e 
   */
  swichNav(e: any) {
    var that = this;
    if (this.data.currentTab === e.currentTarget.dataset.current) {
    } else {
      that.setData({
        currentTab: e.currentTarget.dataset.current
      })
    }
  },
  gotoGoodsClassifyDetail(param: any): void {
    wx.navigateTo({
      url: '/pages/goodsClassifyDetail/goodsClassifyDetail',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { 
          type: param.currentTarget.dataset.type,
          name: param.currentTarget.dataset.name })
      }
    })
  },
  gotoGoodsDetail(param: any): void { // 打开商品详情
    wx.navigateTo({
      url: '/pages/goods/goodsDetail/goodsDetail',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { goodsId: param.currentTarget.dataset.id })
      }
    })
  },
  gotoStoreClassifyList(param: any): void {
    wx.navigateTo({
      url: '/pages/storeClassifyList/storeClassifyList',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { 
          type: param.currentTarget.dataset.type, 
          name: param.currentTarget.dataset.name })
      }
    })
  },
  doSearch(param: any): void {
    wx.navigateTo({
      url: '/pages/searcher/searchHistory/searchHistory',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { keywords: param.currentTarget.dataset.keywords })
      }
    })
  },
  doScanCode(): void {
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        // console.error(JSON.stringify(res))
        let path = res.path
        // console.error("res.path: " + path)
        let pagePath = path.substring(0, path.indexOf("?"))
        // console.error("res.path: substr0 = " + pagePath)
        let param: String = path.substring(path.indexOf("=") + 1)
        // console.error("res.path: substr1 = " + param)
        var paramArr: string[];
        if (param.includes("%")) {
          paramArr = param.split('%')
        } else {
          paramArr = param.split('&')
        }
        // console.error("paramArr[0]: " + paramArr[0])
        // console.error("paramArr[1]: " + paramArr[1])
        // 跳转
        wx.navigateTo({
          url: "/" + pagePath,
          events: {
          },
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据  
            res.eventChannel.emit('acceptDataFromOpenerPage', { storeId: paramArr[0] })
          }
        })
      }
    })
  },
})